package la.iok.aone.monitor.youtube.listener;

import java.io.File;

import la.iok.aone.monitor.youtube.event.ExcelResourceChangeEvent;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 监听文件夹变动
 * @author bunco
 */
@Component
public class ImportFileAlterationListener implements FileAlterationListener {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private ApplicationContext context;

	public void onStart(FileAlterationObserver observer) {

	}

	public void onDirectoryCreate(File directory) {
		logger.debug("on directory create: {}", directory.getPath());
	}

	public void onDirectoryChange(File directory) {
		logger.debug("on directory change: {}", directory.getPath());
	}

	public void onDirectoryDelete(File directory) {
		logger.debug("on directory delete: {}", directory.getPath());
	}

	/**
	 * 当监听文件夹下有新文件创建时触发
	 * TODO 1. 生成导入任务，存储进数据库。
	 *      2. 发出通知，通知异步导入线程进行导入操作。并将导入任务的ID传递给异步导入线程
	 * @param file 新文件
	 */
	public void onFileCreate(File file) {
		logger.debug("on file create: {}", file.getPath());
		context.publishEvent(new ExcelResourceChangeEvent(this, file));
	}

	/**
	 * 当监听文件夹下有文件修改时触发
	 * TODO 1. 生成导入任务，存储进数据库。
	 *      2. 发出通知，通知异步导入线程进行导入操作。并将导入任务的ID传递给异步导入线程
	 * @param file 发生改变的文件
	 */
	public void onFileChange(File file) {
		logger.debug("on file change: {}", file.getPath());
		context.publishEvent(new ExcelResourceChangeEvent(this, file));
	}

	public void onFileDelete(File file) {
		logger.debug("on file delete: {}", file.getPath());
	}

	public void onStop(FileAlterationObserver observer) {

	}
}
